package cn.lyjuan.dwz_manage.core.java.taglibs;

import cn.lyjuan.dwz_manage.core.java.cst.TypeCst;
import org.springframework.security.taglibs.authz.AbstractAuthorizeTag;
import org.springframework.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import java.io.IOException;

/**
 * Created by chad on 2016/9/14.
 */
public class JspUrlTag extends AbstractAuthorizeTag implements Tag
{
    private   Tag         parent;
    protected PageContext pageContext;
    /**
     * 请求URL地址，不带后缀，由配置决定
     */
    private   String      url;
    /**
     * 请求参数
     */
    private   String      data;
    /**
     * 不需要权限认证
     */
    private   boolean     skipAuth;
    /**
     * 是否有权限
     */
    private   boolean     authorized;

    @Override
    public int doStartTag() throws JspException
    {
        try
        {
            this.authorized = super.authorize();

            if (this.skipAuth || this.authorized)// 有权限
            {
                StringBuilder result = new StringBuilder(this.url);

                if (!StringUtils.isEmpty(this.data))// 拼接参数
                    result.append("?").append(this.data);
                // 输出
                this.pageContext.getOut().write(result.toString());
            } else
            {
                this.pageContext.getOut().write("javascript:alertMsg.error('无权操作');");
            }

            return SKIP_BODY;// 跳过内容
        } catch (IOException e)
        {
            throw new JspException(e);
        }
    }

    @Override
    public int doEndTag() throws JspException
    {
        return EVAL_PAGE;
    }

    @Override
    public void setUrl(String url)
    {
        // 拼接后缀
        this.url = url = url + this.getRequest().getAttribute(TypeCst.RequestAttributes.HTTP_SUFFIX_NAME);
        // 权限验证需要URL
        if (!url.startsWith("/")) url = "/" + url;
        super.setUrl(url);
    }

    @Override
    public void release()
    {
        this.pageContext = null;
        this.parent = null;
    }

    @Override
    public void setParent(Tag tag)
    {
        this.parent = tag;
    }
    @Override
    public Tag getParent()
    {
        return this.parent;
    }
    public void setData(String data) {this.data = data;}
    public void setSkipAuth(boolean skipAuth) {this.skipAuth = skipAuth;}
    @Override
    protected ServletRequest getRequest() {return this.pageContext.getRequest();}
    @Override
    protected ServletResponse getResponse() {return this.pageContext.getResponse();}
    @Override
    protected ServletContext getServletContext() {return this.pageContext.getServletContext();}
    public void setPageContext(PageContext pageContext) {this.pageContext = pageContext;}
}
